<template>
    <div class="teaching-steps-container">
      <el-card shadow="hover" class="table-card">
        <el-table
          :data="displayedSteps"
          style="width: 100%"
          border
          :row-class-name="tableRowClassName"
          stripe
          v-loading="loading"
        >
          <el-table-column prop="linkName" label="环节名称" width="150" header-align="center" align="center">
            <template #default="{ row, $index }">
              <span v-if="!isEditMode" class="animated-text">
                {{ shouldShowRow($index) ? row.displayLinkName : '' }}
              </span>
              <el-input
                v-else
                v-model="row.linkName"
                @blur="updateStep(row)"
                size="small"
                placeholder="输入环节名称"
              />
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容描述" header-align="center">
            <template #default="{ row, $index }">
              <span v-if="!isEditMode" class="animated-text">
                {{ shouldShowRow($index) ? row.displayContent : '' }}
              </span>
              <el-input
                v-else
                type="textarea"
                :rows="3"
                v-model="row.content"
                @blur="updateStep(row)"
                size="small"
                placeholder="输入内容描述"
              />
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间(分钟)" width="120" header-align="center" align="center">
            <template #default="{ row, $index }">
              <span v-if="!isEditMode" class="animated-text">
                {{ shouldShowRow($index) ? row.displayTime : '' }}
              </span>
              <el-input-number
                v-else
                v-model="row.time"
                :min="1"
                :max="60"
                @blur="updateStep(row)"
                size="small"
                controls-position="left"
                style="width:80px;"
              />
            </template>
          </el-table-column>
          <el-table-column 
            label="操作" 
            width="120" 
            v-if="isEditMode && allContentShown" 
            header-align="center" 
            align="center">
            <template #default="{ $index }">
              <el-button
                type="primary"
                size="small"
                @click="removeStep($index)"
                :disabled="steps.length <= 1"
                plain
              >
                <el-icon style="position: relative;left:2px;"><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
  
      <div class="button-group">
        <div class="control-panel" v-if="isEditMode && allContentShown">
          <el-button type="primary" @click="addNewStep" plain round>
            <el-icon><Plus /></el-icon>
            添加环节
          </el-button>
          <el-button type="success" @click="saveSteps" plain round>
            <el-icon><Upload /></el-icon>
            保存修改
          </el-button>
        </div>
  
        <div class="view-control" v-if="!isEditMode && allContentShown">
          <el-button type="warning" @click="enterEditMode" plain round>
            <el-icon><Edit /></el-icon>
            编辑内容
          </el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Plus, Upload, Edit, Delete } from '@element-plus/icons-vue'
  import { useCounterStore } from '@/stores/counter'
  import axios from 'axios'
  
  const Store = useCounterStore()
  
  interface TeachingStep {
    linkName: string
    content: string
    time: number
    displayLinkName: string
    displayContent: string
    displayTime: string
    isAnimating: boolean
    showRow: boolean // 新增：控制行是否显示
  }
  
  const props = defineProps({
    initialSteps: {
      type: Array as () => Omit<TeachingStep, 'displayLinkName' | 'displayContent' | 'displayTime' | 'isAnimating' | 'showRow'>[],
      default: () => []
    }
  })
  
  const emit = defineEmits<{
  (e: 'update:steps', steps: Array<{ linkName: string; content: string; time: number }>): void;
  (e: 'save', steps: Array<{ linkName: string; content: string; time: number }>): void;
  (e: 'toNextStep', param: number): void;
}>();
  
  const steps = ref<TeachingStep[]>([])
  const isEditMode = ref(false)
  const currentStepIndex = ref(0)
  const animationInterval = ref<NodeJS.Timeout | null>(null)
  const loading = ref(false)
  const hasShownAnimation = ref(false)
  const allContentShown = ref(false)
  
  const displayedSteps = computed(() => {
    return steps.value
  })
  
  // 检查是否应该显示该行
  const shouldShowRow = (index: number) => {
    return steps.value[index]?.showRow || false
  }
  
  // 初始化数据
  onMounted(async () => {
    await initTeachingSteps()
  })
  
  // 初始化教学步骤数据
  const initTeachingSteps = async () => {
    loading.value = true
    try {
      if (!Store.AITeach?.Step3?.content || Store.AITeach.Step3.content.length === 0) {
        await fetchTeachingStepsFromAPI()
      } else {
        steps.value = Store.AITeach.Step3.content.map((step: any) => ({
          ...step,
          displayLinkName: step.linkName || '未命名环节',
          displayContent: step.content || '暂无内容描述',
          displayTime: (Number(step.time) || 5).toString(),
          isAnimating: false,
          showRow: true // 直接显示模式默认显示所有行
        }))
        allContentShown.value = true
      }
    } catch (error) {
      ElMessage.error('初始化教学步骤失败')
      console.error(error)
      steps.value = [{
        ...createDefaultStep(),
        showRow: true
      }]
      allContentShown.value = true
    } finally {
      loading.value = false
    }
  }
  
  // 创建默认步骤
  const createDefaultStep = (): Omit<TeachingStep, 'showRow'> => ({
    linkName: '导入新课',
    content: '教师使用日常生活中的例子引导学生思考',
    time: 5,
    displayLinkName: '导入新课',
    displayContent: '教师使用日常生活中的例子引导学生思考',
    displayTime: '5',
    isAnimating: false
  })
  
  // 从API获取教学步骤数据
  const fetchTeachingStepsFromAPI = async () => {
    try {
      const response = await axios({
        url: "https://m1.apifoxmock.com/m1/5997017-0-default/teacher/design/timeallocation",
        method: "GET",
        params: {
          text: Store.$state.AIClassQuestion
        }
      })
  
      if (response.data.code === 200) {
        const timeTable = Array.isArray(response.data.data.timeTable)
          ? response.data.data.timeTable
          : []
  
        const formattedSteps = timeTable.map((item: any) => ({
          linkName: item.linkName || '未命名环节',
          content: item.content || '暂无内容描述',
          time: Number(item.time) || 5
        }))
  
        Store.addAIteachStep3(formattedSteps)
        
        // 初始化时所有行都不显示
        steps.value = formattedSteps.map((step:any) => ({
          ...step,
          displayLinkName: '',
          displayContent: '',
          displayTime: '',
          isAnimating: false,
          showRow: false
        }))
  
        startAnimation()
      } else {
        throw new Error(response.data.message || 'API返回错误')
      }
    } catch (error) {
      console.error("获取数据失败:", error)
      throw error
    }
  }
  
  // 进入编辑模式
  const enterEditMode = () => {
    isEditMode.value = true
    steps.value.forEach(step => {
      step.displayLinkName = step.linkName
      step.displayContent = step.content
      step.displayTime = step.time.toString()
    })
  }
  
  // 表格行样式
  const tableRowClassName = ({ row }: { row: TeachingStep }) => {
    return row.isAnimating ? 'animating-row' : ''
  }
  
  // 添加新环节
  const addNewStep = () => {
    steps.value.push({
      ...createDefaultStep(),
      showRow: true
    })
    ElMessage.success('已添加新环节')
  }
  
  // 删除环节
  const removeStep = (index: number) => {
    if (steps.value.length <= 1) {
      ElMessage.warning('至少保留一个环节')
      return
    }
    steps.value.splice(index, 1)
    ElMessage.success('已删除环节')
  }
  
  // 更新环节
  const updateStep = (step: TeachingStep) => {
    step.displayLinkName = step.linkName
    step.displayContent = step.content
    step.displayTime = step.time.toString()
    emit('update:steps', steps.value.map(s => ({
      linkName: s.linkName,
      content: s.content,
      time: s.time
    })))
  }
  
  // 保存修改
  const saveSteps = () => {
    Store.addAIteachStep3(steps.value.map(s => ({
      linkName: s.linkName,
      content: s.content,
      time: s.time
    })))
    
    emit('save', steps.value.map(s => ({
      linkName: s.linkName,
      content: s.content,
      time: s.time
    })))
    ElMessage.success('保存成功')
    isEditMode.value = false
    hasShownAnimation.value = true
  }
  
  // 开始动画
  const startAnimation = () => {
    if (hasShownAnimation.value) return
  
    const animateStep = (stepIndex: number) => {
      if (stepIndex >= steps.value.length) {
        stopAnimation()
        hasShownAnimation.value = true
        allContentShown.value = true
        console.log('所有动画完成，准备触发下一步') // 调试信息
      // 只在自动动画完成时触发，不在保存时重复触发
      if (!isEditMode.value) {
        emit('toNextStep', 4)
      }
        return
      }
  
      const step = steps.value[stepIndex]
      step.isAnimating = true
      step.showRow = true // 显示当前行
      step.displayLinkName = ''
      step.displayContent = ''
      step.displayTime = ''
  
      animateText(step.linkName, 'displayLinkName', step).then(() => {
        return animateText(step.content, 'displayContent', step)
      }).then(() => {
        return animateText(step.time.toString(), 'displayTime', step)
      }).then(() => {
        step.isAnimating = false
        currentStepIndex.value = stepIndex
        if (currentStepIndex.value < steps.value.length - 1) {
          animationInterval.value = setTimeout(() => {
            animateStep(currentStepIndex.value + 1)
          }, 500)
        } else {
          allContentShown.value = true
          console.log('最后一个步骤动画完成')
          emit('toNextStep',4)
        }
      })
    }
  
    animateStep(0)
  }
  
  // 停止动画
  const stopAnimation = () => {
    if (animationInterval.value) {
      clearTimeout(animationInterval.value)
      animationInterval.value = null
    }
    steps.value.forEach(step => {
      step.isAnimating = false
    })
  }
  
  // 文字动画效果
  const animateText = (
    text: string, 
    property: 'displayLinkName' | 'displayContent' | 'displayTime', 
    step: TeachingStep
  ) => {
    return new Promise<void>(resolve => {
      let index = 0
      const timer = setInterval(() => {
        if (index < text.length) {
          step[property] = text.substring(0, index + 1)
          index++
        } else {
          clearInterval(timer)
          resolve()
        }
      }, 50)
    })
  }
  </script>
  
  <style scoped>
  .teaching-steps-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
  }
  
  .table-card {
    margin-bottom: 20px;
    border-radius: 12px;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  }
  
  .button-group {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .control-panel, .view-control {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 15px;
    flex-wrap: wrap;
  }
  
  .animated-text {
    transition: all 0.3s ease;
    font-size: 14px;
  }
  
  :deep(.el-table) {
    font-size: 14px;
    border-radius: 8px;
    overflow: hidden;
  }
  
  :deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: bold;
    height: 50px;
  }
  
  :deep(.el-table .animating-row) {
    background-color: #f0f7ff;
    transition: all 0.3s ease;
  }
  
  :deep(.el-table .animating-row td) {
    background-color: #f0f7ff !important;
  }
  
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #fafafa;
  }
  
  :deep(.el-table td) {
    padding: 15px 0;
    transition: background-color 0.3s;
  }
  
  :deep(.el-table .cell) {
    white-space: pre-wrap;
    word-break: break-word;
    line-height: 1.6;
    padding: 0 10px;
  }
  
  :deep(.el-textarea__inner) {
    min-height: 80px !important;
    font-size: 14px;
  }
  
  :deep(.el-input__inner), 
  :deep(.el-input-number__decrease),
  :deep(.el-input-number__increase) {
    height: 32px;
    line-height: 32px;
  }
  
  :deep(.el-button) {
    font-size: 14px;
    padding: 8px 15px;
  }
  
  :deep(.el-icon) {
    vertical-align: middle;
    margin-right: 5px;
  }
  
  @media (max-width: 768px) {
    .control-panel, .view-control {
      gap: 10px;
    }
    
    :deep(.el-table-column) {
      width: auto !important;
    }
  }
  </style>